package com.xuecheng.search.listener;

import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.search.service.SearchService;
import com.xuecheng.web.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者监听队列
 *
 * @author 七安
 */
@Component
@Slf4j
public class MessageListener {

    @Autowired
    private SearchService searchService;

    /**
     * 接收队列消息，进行Es数据同步
     *
     * @param coursePubId 课程发布id
     */
    @RabbitListener(bindings =
    @QueueBinding(value = @Queue("course-index-queue"),
            exchange = @Exchange(name = "content-exchange", type = ExchangeTypes.TOPIC),
            key = "course-pub"))
    public void fuckListener(Long coursePubId) throws BusinessException, IOException {
        //检测参数
        if (coursePubId == null) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        //调用service
        searchService.cogradientIndex(coursePubId);

    }

    /**
     * 监听下架课程id，进行同步
     * @param coursePubId 课程发布id
     */
    @RabbitListener(bindings =
    @QueueBinding(value = @Queue("course-delete-queue"),
            exchange = @Exchange(name = "content-exchange", type = ExchangeTypes.TOPIC),
            key = "course-soldOut"))
    public void deleteListener(Long coursePubId) throws IOException {
        searchService.deleteCourse(coursePubId);
    }
}
